using System;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using Kiwi.Container.Application;

namespace Kiwi.Container.Web
{
    public class ContainerModule : IHttpModule
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(HttpApplication context)
        {
            var container = ContainerManager.Root;
            if (container.Extensions.Any(e => e is IHttpHandlerDependencyInjector))
            {
                context.PreRequestHandlerExecute += HandleInjectHandlerDependencies;
            }

            if (container.Extensions.Any(a => a is IHttpSessionContainerActivator))
            {
                context.PostRequestHandlerExecute += HandleSessionContainerActivation;
            }

            if (container.Extensions.Any(a => a is IHttpRequestContainerActivator))
            {
                context.EndRequest += HandleRequestContainerActivation;
            }
        }

        #endregion

        private static void HandleInjectHandlerDependencies(object sender, EventArgs e)
        {
            var handler = HttpContext.Current.Handler;

            var container = ContainerManager.Current;

            foreach (
                var injector in
                    container.Extensions.Where(ext => ext is IHttpHandlerDependencyInjector).Cast
                        <IHttpHandlerDependencyInjector>())
            {
                injector.InjectDependencies(container, handler);
            }
        }

        private static void HandleSessionContainerActivation(object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            if (context == null)
            {
                return;
            }
            var session = context.Session;
            if (session == null)
            {
                return;
            }

            var stateProvider = SessionStateUtility.GetHttpSessionStateFromContext(context) as HttpSessionStateContainer;

            if ((stateProvider != null) && stateProvider.IsAbandoned)
            {
                HttpSessionContainerActivator.ReleaseSessionContainer(session);
            }
        }

        private static void HandleRequestContainerActivation(object sender, EventArgs e)
        {
            var context = HttpContext.Current;
            if (context == null)
            {
                return;
            }
            HttpRequestContainerActivator.ReleaseRequestContainer(context);
        }
    }
}